import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Prisma, course_chapter } from '@prisma/client';
import { statSync } from 'fs';
@Injectable()
export class CourseChapterService {
    constructor(private readonly prisma: PrismaService) {}
   async getChapter(id: string) {
        return await this.prisma.course_chapter.findMany({
            where: {
                courseId: id
            },
            select: {
                id: true,
                title: true,
                desc: true,
                createdAt: true,
                updatedAt: true
            }
        }).then((chapters) => {
            return Promise.all(chapters.map(async (chapter) => {
                const contentCount = await this.prisma.course_content.count({
                    where: {
                        chapterId: chapter.id
                    }
                }) ;
               await this.prisma.course_chapter.update({
                    where: {
                        id: chapter.id
                    },
                    data: {
                        contentCount: contentCount
                    }
                });
                return {
                    ...chapter,
                    contentCount: contentCount
                };
            }));

        })

        // const chaptersWithCount = await Promise.all(
        //     chapters.map(async (item) => {
        //         const count = await this.prisma.course_content.count({
        //             where: {
        //                 chapterId: item.id
        //             }
        //         });
        //         return {
        //             ...item,
        //             contentCount: count
        //         };
        //     })
        // );

        // return chaptersWithCount;
    }
   async getNextChapter(chapterId: string){
         const chapter = await this.prisma.course_chapter.findFirst({
            where: {
                id:chapterId
            },
        });
        if(!chapter){
            throw new Error('chapter not found');
        }
        const chapterS= await this.prisma.course_chapter.findMany({
            where: {
                courseId:chapter.courseId
            },
            select:{
                id:true,
              }
        });
        const chapterIds = chapterS.map(chapter => chapter.id);
        const index = chapterIds.indexOf(chapterId);
        if(index === chapterIds.length - 1){
            throw new Error('暂无更多课程');
        }
        return chapterIds[index + 1];
    }
}
